﻿using HDJ.Framework.Core;
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;

[CustomEditor(typeof(ObjectReference))]
public class ObjectReferenceEditor : Editor {

    private bool isFold = false;
   
    public override void OnInspectorGUI()
    {
        ObjectReference obj = (ObjectReference)target;
          List<string> nameList = new List<string>();
        List<string> repeatNames= new List<string>();

    GUILayout.Space(6);
        //GUILayout.BeginVertical("box");
        isFold = EditorGUILayout.Foldout(isFold, "GameObject Reference");

        if (isFold)
        {
            GUILayout.BeginHorizontal();
            GUILayout.FlexibleSpace();
            if (GUILayout.Button("+", GUILayout.Width(50)))
            {
                NameToObject temp = new NameToObject();
                temp.name = "";
                temp.gameObject = null;
                obj.referenceList.Add(temp);
            }
            GUILayout.EndHorizontal();

            for (int i = 0; i < obj.referenceList.Count; i++)
            {
                NameToObject item = obj.referenceList[i];
                if (string.IsNullOrEmpty(item.name)&& item.gameObject && (!string.IsNullOrEmpty(item.gameObject.name)))
                {
                    item.name = item.gameObject.name;
                }
                GUILayout.BeginHorizontal("box");
                item.name = EditorDrawGUIUtil.DrawBaseValue("Name", item.name).ToString();
                item.gameObject = (GameObject)EditorGUILayout.ObjectField(name, item.gameObject, typeof(GameObject), true);

                if (GUILayout.Button("-", GUILayout.Width(50)))
                {
                    obj.referenceList.RemoveAt(i);
                    break;
                }
                GUILayout.EndHorizontal();
                obj.referenceList[i] = item;

                if (nameList.Contains(item.name))
                {
                    repeatNames.Add(item.name);
                }
                else
                    nameList.Add(item.name);
            }
            if(repeatNames.Count>0)
            EditorGUILayout.HelpBox("名字重复了！\n"+ string.Join(",",repeatNames.ToArray()), MessageType.Error);

           
        }

        if (GUI.changed)
        {
            EditorUtility.SetDirty(obj);
            EditorSceneManager.MarkAllScenesDirty();
        }
           
        //GUILayout.EndVertical();

    }
}
